package com.redisson.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Created by cheng on 2020/7/25.
 */
@Component
public class DynamicToSpring implements ApplicationContextAware {

    private ApplicationContext applicationContext;
    private AutowireCapableBeanFactory autowireCapableBeanFactory;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        this.autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
    }

    public Object createBean(Class clazz){
        try {
            Object bean = autowireCapableBeanFactory.getBean(clazz);
            if (bean == null) {
                return autowireCapableBeanFactory.createBean(clazz, 2, true);
            } else {
                return bean;
            }
        }catch (Throwable t){
            return autowireCapableBeanFactory.createBean(clazz, 2, true);
        }
    }

    public void autowire(Object bean){
        autowireCapableBeanFactory.autowireBean(bean);
    }
}
